package design.mode.atomic.accountdemo;

import java.util.concurrent.atomic.AtomicInteger;

public class Account {
    private int balance;
    private AtomicInteger transferState;

    public Account(int balance) {
        this.balance = balance;
        this.transferState = new AtomicInteger(0);
    }

    public void transfer(Account otherAccount, int amount) {
        while (true) {
            if (transferState.compareAndSet(0, 1)) {
                if (this.balance >= amount) {
                    this.balance -= amount;
                    otherAccount.balance += amount;
                    transferState.set(0); // 成功执行转账，重置状态
                    break;
                } else {
                    transferState.set(0); // 转账失败，重置状态
                    break;
                }
            }
        }
    }
}